package hb.watcher.monitor;

import java.io.Serializable;
import java.sql.Array;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.os.AsyncTask;

import com.mysql.jdbc.Statement;

public class DBConnection implements Serializable {

	private String Url;
	private String DBName;
	private String UserName;
	private String PassWord;
	
	private String LastError;
	
	private Connection conn;

	
	public List<CharsActivity> CharsActivity_List = new ArrayList<CharsActivity>();
	public List<ChatActivity> ChatActivity_List = new ArrayList<ChatActivity>();
	
	public WatchMyToonActivity m_master;
	public DBConnection(String Url, String DBName, String UserName, String PassWord, WatchMyToonActivity master)
	{
		this.Url = Url;
		this.DBName = DBName;
		this.PassWord = PassWord;
		this.UserName = UserName;
		this.LastError = null;
		this.m_master = master;
	}
	
	public DBConnection(String Url, String DBName, String UserName, String PassWord)
	{
		this.Url = Url;
		this.DBName = DBName;
		this.PassWord = PassWord;
		this.UserName = UserName;
		this.LastError = null;
	}
	

	
	public void Register(CharsActivity newChars)
	{
		CharsActivity_List.add(newChars);
	}
	
	public void Register(ChatActivity newChatt)
	{
		ChatActivity_List.add(newChatt);
	}

	public boolean Connect()
	{
		try
		{
			Driver d = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();
			DriverManager.registerDriver(d);
			conn = DriverManager.getConnection("jdbc:mysql://" + this.Url + "/" + this.DBName, this.UserName, this.PassWord);
			this.LastError = null;
			return true;
			
		}catch(Exception ex)
		{
			this.LastError = ex.getLocalizedMessage();
			return false;
		}
	
	}
	
	public ResultSet DBSyn(boolean get, String SQLCommand)
	{
		ResultSet returnset = null;
			try
				{
					if(!conn.isClosed())
					{
					 
						Statement stmt = (Statement)conn.createStatement();
						if(get)
							returnset = stmt.executeQuery(SQLCommand);
						else
							stmt.execute(SQLCommand);
						
					}
					
				
				}catch(Exception ex)
				{
					
				}
		
			return returnset;
	
		
	}
	
	public void CloseConnection()
	{
		try {
			conn.close();
		} catch (SQLException e) {
			
		}
	}

	public void StartUpdater()
	{
		Updater upt = new Updater();
		upt.execute();
	}
	
	public String getLastError()
	{
		return this.LastError;
	}
	
	public void clearError()
	{
		this.LastError = null;
	}
	
	public boolean IsConnected()
	{
		try {
			return !conn.isClosed();
		} catch (Exception e) {
			return false;
		}
	}
	
	private class Updater extends AsyncTask<Void, Void, Void>
	{
		boolean running = true;
		final Config conf = new Config();
    	
		public ResultSet DBSyn(boolean get, String SQLCommand)
		{
			ResultSet returnset = null;
				try
					{
						if(!conn.isClosed())
						{
						 
							Statement stmt = (Statement)conn.createStatement();
							if(get)
								returnset = stmt.executeQuery(SQLCommand);
							else
								stmt.execute(SQLCommand);
							
						}
						
					
					}catch(Exception ex)
					{
						
					}
			
				
				return returnset;
			
		}
		
		public boolean notify = false;
		
		public boolean notEmpty(String s) {
		   	 return (s != null && s.length() > 0);
		   	}
		
		@Override
		protected Void doInBackground(Void... params) {
			
			while(running)
			{
				try
				{
				conf.load();
				
				boolean notify_say = false;
				boolean notify_yell = false;
				boolean notify_guild = false;
				boolean notify_whisper = true;
				boolean notify_bg = false;
				boolean notify_party = false;
				
				if(notEmpty(conf.get("notify_say")))
				{
		    		if(conf.get("notify_say").equals("true"))
		    			notify_say = true;
		    		else
		    			notify_say = false;
		    	}
				
				if(notEmpty(conf.get("notify_yell")))
				{
		    		if(conf.get("notify_yell").equals("true"))
		    			notify_yell = true;
		    		else
		    			notify_yell = false;
		    	}
				
				if(notEmpty(conf.get("notify_guild")))
				{
		    		if(conf.get("notify_guild").equals("true"))
		    			notify_guild = true;
		    		else
		    			notify_guild = false;
		    	}
				
				if(notEmpty(conf.get("notify_whisper")))
				{
		    		if(conf.get("notify_whisper").equals("true"))
		    			notify_whisper = true;
		    		else
		    			notify_whisper = false;
		    	}else
		    		notify_whisper = true;
				
				
				if(notEmpty(conf.get("notify_bg")))
				{
		    		if(conf.get("notify_bg").equals("true"))
		    			notify_bg = true;
		    		else
		    			notify_bg = false;
		    	}
				
				if(notEmpty(conf.get("notify_party")))
				{
		    		if(conf.get("notify_party").equals("true"))
		    			notify_party = true;
		    		else
		    			notify_party = false;
		    	}
				
				
				
				
				
				
				
				for(int i = 0; i < CharsActivity_List.size(); i++)
				{
					if(!CharsActivity_List.get(i).InitDone())
						CharsActivity_List.get(i).Init();
					
					
					String statement = CharsActivity_List.get(i).getStatement();
					CharsActivity_List.get(i).Update(DBSyn(true, statement));
				}
				
				for(int i = 0; i < ChatActivity_List.size(); i++)
				{
					if(!ChatActivity_List.get(i).InitDone())
						ChatActivity_List.get(i).Init();
					
					
					String statement = ChatActivity_List.get(i).getStatement();
					ResultSet sending = DBSyn(true, statement);
					
		
					try {
						while(sending.next())
						{
							int msgId = sending.getInt("nMsgId");
							ChatActivity_List.get(i).Update(sending.getString("szMessagePartner"), sending.getString("szMessageText"));
							DBSyn(false, "DELETE FROM `TABMessageReceive` where nMsgId = " + msgId + ";");
						
							if(ChatActivity_List.get(i).getMessageType().equals("WHISPER_MESSAGE") && notify_whisper)
								m_master.sendnotify(ChatActivity_List.get(i), "New Whispermessage", "New Whispermessage", sending.getString("szMessagePartner") + " has send a new Message");
						
							if(ChatActivity_List.get(i).getMessageType().equals("SAY_MESSAGE") && notify_say)
								m_master.sendnotify(ChatActivity_List.get(i), "New Saymessage", "New Saymessage", sending.getString("szMessagePartner") + " has send a new Message");
						
							if(ChatActivity_List.get(i).getMessageType().equals("GUILD_MESSAGE") && notify_guild)
								m_master.sendnotify(ChatActivity_List.get(i), "New Guildmessage", "New Guildmessage", sending.getString("szMessagePartner") + " has send a new Message");
						
							if(ChatActivity_List.get(i).getMessageType().equals("YELL_MESSAGE") && notify_yell)
								m_master.sendnotify(ChatActivity_List.get(i), "New Yellmessage", "New Yellmessage", sending.getString("szMessagePartner") + " has send a new Message");
						
							if(ChatActivity_List.get(i).getMessageType().equals("BATTLEGROUND_MESSAGE") && notify_bg)
								m_master.sendnotify(ChatActivity_List.get(i), "New Battlegroundmessage", "New Battlegroundmessage", sending.getString("szMessagePartner") + " has send a new Message");
						
							if(ChatActivity_List.get(i).getMessageType().equals("PARTY_MESSAGE") && notify_party)
								m_master.sendnotify(ChatActivity_List.get(i), "New Partymessage", "New Partymessage", sending.getString("szMessagePartner") + " has send a new Message");
						
						}
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					ChatActivity_List.get(i).Update();
					List<String> toSend = ChatActivity_List.get(i).GetNewMessages();
					
					for(int x = 0; x < toSend.size(); x++)
					{
						DBSyn(false, toSend.get(x));
					}
				}
				}catch (Exception ex)
				{
					
				}
				
				
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				}
			}
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Void... values) {	
		}
	}

}
